package com.aksu.wiki.service;


import com.aksu.wiki.domain.Category;
import com.aksu.wiki.domain.CategoryExample;
import com.aksu.wiki.mapper.CategoryMapper;
import com.aksu.wiki.req.CategoryQueryReq;
import com.aksu.wiki.req.CategorySaveReq;
import com.aksu.wiki.resp.CategoryQueryResp;
import com.aksu.wiki.resp.PageResp;
import com.aksu.wiki.util.CopyUtil;
import com.aksu.wiki.util.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {

    @Resource
    private SnowFlake snowFlake;



    private static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);


    @Resource
    private CategoryMapper categoryMapper;



    public PageResp<CategoryQueryResp> getList(CategoryQueryReq req) {

        PageHelper.startPage(req.getPage(), req.getSize());

        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
//        if(!ObjectUtils.isEmpty(req.getName())){
//            criteria.andNameLike("%"+req.getName()+"%");
//        }

        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        LOG.info("总行数:{}",pageInfo.getTotal());
        LOG.info("总页数:{}",pageInfo.getPages());

        PageResp<CategoryQueryResp> pageResp = new PageResp();

        List<CategoryQueryResp> categoryResps = CopyUtil.copyList(categoryList, CategoryQueryResp.class);
        pageResp.setList(categoryResps);
        pageResp.setTotal(pageInfo.getTotal());

        return  pageResp;

    }

    public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        // 列表复制
        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        return list;
    }


    /**
     * 保存
     */
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        } else {
            // 更新
            LOG.info("更新category:{}",category);
            categoryMapper.updateByPrimaryKey(category);
        }
    }

    public void delete(Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }

}
